const app = getApp()
var netUtil = require("../../utils/netUtil.js"); //require引入
var QQMapWX = require('../../utils/qqmap-wx-jssdk.js');
var qqmapsdk;
var page = 1;
Page({
  data: {
    tabbar: {},
    nvabarData: {
      showCapsule: 0, //是否显示左上角图标   1表示显示    0表示不显示
      title: '首页', //导航栏 中间的标题
    },
    // 此页面 页面内容距最顶部的距离
    height: app.globalData.height * 2 + 20, 
    imgUrls: ["/image/banner.png", "/image/banner.png"],
    province: '',
    city: '',
    latitude: '',
    longitude: '',
    schoolList:[],
    isShow:true,
    isGzh:true,
    urlImg: app.globalData.urlImg,
    provinceList:[],
    cityList:[],
    cityId:'',
    indexValue:[0,0],
    isCityShow:true,
    words:'',

    
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //隐藏系统tabbar
    wx.hideTabBar();
    wx.showLoading({
      title: '加载中',
    })
    
    if (options.union_user_id) {//海报分享
      console.log("海报分享")
      console.log(options.union_user_id)
      this.setData({
        union_user_id: options.union_user_id
      })
    }
    

    app.editTabbar();
    qqmapsdk = new QQMapWX({
      key: 'Z3NBZ-O4C3X-3XW4O-7YU7Y-SRRGJ-KCF3O' //这里自己的key秘钥进行填充
    });
    this.getCityList()
    this.getUserLocation();
    this.login();
    
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    page=1
    this.setData({
      schoolList: []
    })
   
    // 
    this.getBanner();
    this.getSchool(page);
    
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  toStudnentCenter(){
    wx.navigateTo({
      url: '/pages/studentCenter/studentCenter',
    })
  },
  getWord(e){
    this.setData({
      words: e.detail.value,
    })
},
  // 获取banner图
  getBanner(){
    netUtil.postData('carousel/list',{page:1}, (datas) => {
      this.setData({
        bannerList: datas.data.lists
      })
    })
  },
  // banner详情
  bannerDetail(e){
   
    wx.navigateTo({
      url: '/pages/bannerDetail/bannerDetail?id=' + e.currentTarget.id ,
    })
  },
  onReachBottom: function () {
    var that = this;
    if (that.data.is_load==0) return
    // 显示加载图标
    wx.showLoading({
      title: '玩命加载中',
    })
    // 页数+1
    page = page + 1;
    this.getSchool(page)
  },
  // 获取推荐
  getSchool(page){
    let param={
      page: page
    }
    netUtil.postData('school/list',param, (datas) => {
     
      const oldData = this.data.schoolList;
      this.setData({
        schoolList: oldData.concat(datas.data.lists),
        is_load: datas.data.is_load
      })
    })
  },
  // 微信登录
  login() {
    var that = this
    wx.login({
      success(res) {
        if (res.code) {
          let data = {
            code: res.code
          }
          console.log(res.code)
          // 获取token
          netUtil.postData('home/requestSession', data, (datas) => {
            // that.getUserInfo(res.code, datas.data.token);
            if (datas.code==1){
              wx.setStorageSync("token", datas.data.token);
              // 绑定邀请人
              if (that.data.union_user_id){
                that.nvite();
              } 
            }else{
              wx.showToast({
                title: datas.msg,
                icon:'none'
              })
            }            
          })

        } else {
          console.log('登录失败！' + res.errMsg)
        }
      }
    })
  },
  // 绑定上级
  nvite(){
    netUtil.postData('user/bindSuperior', {union_user_id:this.data.union_user_id,token:wx.getStorageSync("token")}, (datas) => {})
  },
  // 搜索
  searchTap(){
    if (!wx.getStorageSync("userInfo")) {
      wx.showModal({
        title: '提示',
        content: '您还未登录，请先登录',
        success(res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/author/author',
            })
          } else if (res.cancel) {
            wx.switchTab({
              url: '/pages/index/index',
            })
          }
        }
      })
      return
    }
    wx.navigateTo({
      url: '/pages/promote/promote?words=' + this.data.words+'&cityId='+this.data.cityId,
    })
  },
  // 学校详情
  detail(e){
    if (!wx.getStorageSync("userInfo")) {
      wx.showModal({
        title: '提示',
        content: '您还未登录，请先登录',
        success(res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/author/author',
            })
          } else if (res.cancel) {
            wx.switchTab({
              url: '/pages/index/index',
            })
          }
        }
      })
      return
    }

    let item = e.currentTarget.dataset.item;
    wx.navigateTo({
        url: '/pages/detail/detail?id=' + item.id 
      })
  },
  // 获取城市
  getCityList(){
    netUtil.postData('city-config/parentList','', (datas) => {
      this.setData({
        provinceList:datas.data.lists,
        cityList: datas.data.lists[0].children
      })
      console.log(datas.data.lists,datas.data.lists[0].children)
    })
  },
  // 授权获取位置
  getUserLocation: function () {
    let vm = this;
    wx.getSetting({
      success: (res) => {
        console.log(JSON.stringify(res))
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
          wx.showModal({
            title: '请求授权当前位置',
            content: '需要获取您的地理位置，请确认授权',
            success: function (res) {
              if (res.cancel) {
                wx.showToast({
                  title: '拒绝授权',
                  icon: 'none',
                  duration: 1000
                })
              } else if (res.confirm) {
                
                wx.openSetting({
                  success: function (dataAu) {
                    if (dataAu.authSetting["scope.userLocation"] == true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 1000
                      })
                      //再次授权，调用wx.getLocation的API
                      vm.getLocation();
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'none',
                        duration: 1000
                      })
                    }
                  }
                })
              }
            }
          })
        } else if (res.authSetting['scope.userLocation'] == undefined) {
          //调用wx.getLocation的API
          vm.getLocation();
        }
        else {
          //调用wx.getLocation的API
          vm.getLocation();
        }
      }
    })
  },
  // 微信获得经纬度
  getLocation: function () {
    let vm = this;
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        console.log(res)
        var latitude = res.latitude
        var longitude = res.longitude
        var speed = res.speed
        var accuracy = res.accuracy;
        vm.getLocal(latitude, longitude)
      },
      fail: function (res) {
        console.log('fail' + JSON.stringify(res))
      }
    })
  },
  // 获取当前地理位置
  getLocal: function (latitude, longitude) {
    let vm = this;
    qqmapsdk.reverseGeocoder({
      location: {
        latitude: latitude,
        longitude: longitude
      },
      success: function (res) {
        let city = res.result.ad_info.city
        wx.setStorageSync("city", city)
        const indexValue=[]
        vm.data.provinceList.forEach((item,index)=>{
          item.children.forEach((data,indexD)=>{
            if(data.label===city){
              indexValue.push(index)
              indexValue.push(indexD)
            }
          })
        })
        const cityList=vm.data.provinceList[indexValue[0]].children
        vm.setData({
          indexValue:indexValue,
          cityList:cityList,
          city:cityList[indexValue[1]].label,
          cityId:cityList[indexValue[1]].value
        })
       
      },
      fail: function (res) {
        console.log(res);
      },
      complete: function (res) {
        // console.log(res);
      }
    });
  },
  isCityShowTap(){
    this.setData({
      isCityShow:false
    })
  },
  citySure(){
    this.setData({
      city:this.data.cityList[this.data.indexValue[1]].label,
      isCityShow:true,
      cityId:this.data.cityList[this.data.indexValue[1]].value
    })
    wx.setStorageSync("city", this.data.city)
  },
  isCityShowHide(){
    this.setData({
      isCityShow:true
    })
  },
  bindChange(e){
    const val = e.detail.value
    this.setData({
      cityList:this.data.provinceList[val[0]].children,
      indexValue:val
    })

  },
  // 保存二维码
  gotoSaveImg() {
    var that = this;   
    wx.downloadFile({
      url:"https://sclyphxcx.ricecs.cn/img/public_img.jpg",
      success: function (res) {
        console.log(res);
        //图片保存到本地
        wx.saveImageToPhotosAlbum({
          filePath: res.tempFilePath,
          success: function (data) {
            wx.showToast({
              title: '保存成功',
              icon: 'success',
              duration: 2000
            })
            wx.setStorageSync("isGzh", true)
            that.setData({
              isGzh:true
            })
          },
          fail: function (err) {

          },
          complete(res) {
            console.log(res);
          }
        })
      }
    })
  },
  hideIsGzh(){
    wx.setStorageSync("isGzh", true)
    this.setData({
      isGzh: true
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})